﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lacrima.Game
{
    /// <summary>
    /// 八数码问题相关算法介绍：
    /// http://www.cnblogs.com/abatei/archive/2008/10/12/1309615.html
    /// 八数码算法：
    /// http://blog.csdn.net/q345852047/article/details/6626684
    /// </summary>
    public partial class EightFigurePuzzle : Form
    {
        public EightFigurePuzzle()
        {
            InitializeComponent();
        }

        private void btnInitialize_Click(object sender, EventArgs e)
        {
            Point startPoint = new Point(0, 0);
            Size size = new Size(122,118);
            string[] seqArray = this.GenSeqArray();
            this.tbInitialization.Text = string.Join(string.Empty, seqArray);
            this.DrawSudoku(startPoint, size, seqArray);
        }

        private string[] GenSeqArray()
        {
            Random rand = new Random();
            HashSet<int> randSet = new HashSet<int>();
            for (int i = 0; i < 9; ++i)
            {
                int randSeq = rand.Next(9);
                while (randSet.Contains(randSeq))
                {
                    randSeq = rand.Next(9);
                }
                randSet.Add(randSeq);
            }
            return randSet.Select(o=>o.ToString()).ToArray();
        }

        private void DrawSudoku(Point startPoint, Size size, string[] seqArray)
        {
            Graphics graphics = this.puzzlePanel.CreateGraphics();
            Pen pen = new Pen(Color.Red, 2);
            SolidBrush brush = new SolidBrush(Color.Green);
            SolidBrush fontBrush = new SolidBrush(Color.Yellow);
            Font font = new Font("雅黑", size.Width * 0.70f);

            for (int row = 0; row < 3; row++)
            {
                for (int column = 0; column < 3; column++)
                {
                    PointF drawPos = new PointF(startPoint.X + size.Width * row, startPoint.Y + size.Height * column);
                    graphics.DrawRectangle(pen, drawPos.X, drawPos.Y, size.Width, size.Height);
                    graphics.FillRectangle(brush, drawPos.X, drawPos.Y, size.Width, size.Height);
                    if (!seqArray[3 * row + column].Equals("0"))
                    {
                        drawPos.X += 8;
                        drawPos.Y -= 7;
                        graphics.DrawString(seqArray[3 * row + column], font, fontBrush, drawPos);
                    }
                }
            }
        }
    }
}
